package com.mdd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.admin.service.ISystemAuthAdminService;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.service.IStoreService;
import com.mdd.admin.validate.system.SystemAdminCreateValidate;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.Store;
import com.mdd.common.entity.system.SystemAuthAdmin;
import com.mdd.common.enums.RoleEnum;
import com.mdd.common.mapper.StoreMapper;
import com.mdd.common.mapper.system.SystemAuthAdminMapper;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.common.util.ToolUtils;
import com.mdd.common.validate.store.StoreCreateValidate;
import com.mdd.common.validate.store.StoreSearchValidate;
import com.mdd.common.validate.store.StoreStatusValidate;
import com.mdd.common.validate.store.StoreUpdateValidate;
import com.mdd.common.vo.store.AdminUserVo;
import com.mdd.common.vo.store.StoreDetailVo;
import com.mdd.common.vo.store.StoreListedVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 门店实现类
 *
 * @author LikeAdmin
 */
@Service
public class StoreServiceImpl implements IStoreService {

    @Resource
    StoreMapper storeMapper;

    @Resource
    ISystemAuthAdminService iSystemAuthAdminService;

    @Resource
    SystemAuthAdminMapper systemAuthAdminMapper;

    /**
     * 门店列表
     *
     * @param pageValidate   分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<StoreListedVo>
     * @author LikeAdmin
     */
    @Override
    public PageResult<StoreListedVo> list(PageValidate pageValidate, StoreSearchValidate searchValidate) {
        Integer page = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("store_id");

        storeMapper.setSearch(queryWrapper, searchValidate, new String[]{"=:storeCode@store_code:str", "like:storeName@store_name:str", "=:priceType@price_type:str", "=:status:str",});

        IPage<Store> iPage = storeMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<StoreListedVo> list = new LinkedList<>();
        for (Store item : iPage.getRecords()) {
            StoreListedVo vo = new StoreListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            SystemAuthAdmin admin = systemAuthAdminMapper.selectById(item.getUserId());
            vo.setUsername(Objects.nonNull(admin) ? admin.getUsername() : "");
            list.add(vo);
        }
        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 门店详情
     *
     * @param id 主键参数
     * @return Store
     * @author LikeAdmin
     */
    @Override
    public StoreDetailVo detail(Integer id) {
        Store model = storeMapper.selectOne(new QueryWrapper<Store>().eq("store_id", id).eq("is_delete", 0).last("limit 1"));

        Assert.notNull(model, "数据不存在");

        StoreDetailVo vo = new StoreDetailVo();
        BeanUtils.copyProperties(model, vo);
        SystemAuthAdmin admin = systemAuthAdminMapper.selectById(model.getUserId());
        if (Objects.nonNull(admin)) {
            vo.setUserId(model.getUserId());
            vo.setUsername(admin.getUsername());
        }
        return vo;
    }

    /**
     * 门店新增
     *
     * @param createValidate 参数
     * @author LikeAdmin
     */
    @Override
    public void add(StoreCreateValidate createValidate) {
        Assert.isTrue(codeUnique(createValidate.getStoreCode()), "门店编号重复");
        Assert.isTrue(nameUnique(createValidate.getStoreName()), "门店名称重复");

        Store model = new Store();
        BeanUtils.copyProperties(createValidate, model);

        SystemAdminCreateValidate admin = new SystemAdminCreateValidate();
        BeanUtils.copyProperties(createValidate, admin);
        admin.setNickname(createValidate.getUsername());
        admin.setRoleIds(Arrays.asList(RoleEnum.STORE_MANAGE.getCode()));
        admin.setDeptIds(Arrays.asList());
        admin.setPostIds(Arrays.asList());
        admin.setIsDisable(0);
        admin.setIsMultipoint(1);
        Integer userId = iSystemAuthAdminService.add(admin);
        model.setUserId(userId);

        model.setCreateTime(TimeUtils.timestamp());
        storeMapper.insert(model);
    }

    @Override
    public Boolean nameUnique(String storeName) {
        return getNameUnique(storeName, 0);
    }

    @Override
    public Boolean nameUnique(String storeName, Integer storeId) {
        return getNameUnique(storeName, storeId);
    }

    @Override
    public Boolean codeUnique(String storeCode) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_code", storeCode).select("store_id");
        queryWrapper.eq("is_delete", 0).last("limit 1");
        Store model = storeMapper.selectOne(queryWrapper);
        return StringUtils.isNull(model) ? true : false;
    }

    private Boolean getNameUnique(String storeName, Integer storeId) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_name", storeName).select("store_id");
        if (storeId != 0) {
            queryWrapper.ne("store_id", storeId);
        }
        queryWrapper.eq("is_delete", 0).last("limit 1");
        Store model = storeMapper.selectOne(queryWrapper);
        return StringUtils.isNull(model) ? true : false;
    }

    /**
     * 门店编辑
     *
     * @param updateValidate 参数
     * @author LikeAdmin
     */
    @Override
    public void edit(StoreUpdateValidate updateValidate) {
        //Assert.isTrue(codeUnique(updateValidate.getStoreCode()), "门店编号重复");
        //Assert.isTrue(nameUnique(updateValidate.getStoreName()), "门店名称重复");
        Store model = storeMapper.selectOne(new QueryWrapper<Store>().eq("store_id", updateValidate.getStoreId()).eq("is_delete", 0).last("limit 1"));

        Assert.notNull(model, "数据不存在!");
        BeanUtils.copyProperties(updateValidate, model);
        model.setUpdateTime(TimeUtils.timestamp());
        // 修改账号问题
        String username = updateValidate.getUsername();
        AdminUserVo adminVo = getAdminDetail(model.getUserId());
        if (Objects.nonNull(adminVo) && !adminVo.getUsername().equals(username)) {
            SystemAuthAdmin admin = new SystemAuthAdmin();
            admin.setId(model.getUserId());
            admin.setUsername(username);
            String pwd = ToolUtils.makeMd5(updateValidate.getPassword().trim() + adminVo.getSalt());
            admin.setPassword(pwd);
            systemAuthAdminMapper.updateById(admin);
        }
        storeMapper.updateById(model);
    }

    /**
     * 门店删除
     *
     * @param id 主键ID
     * @author LikeAdmin
     */
    @Override
    public void del(Integer id) {
        Store model = storeMapper.selectOne(new QueryWrapper<Store>().eq("store_id", id).eq("is_delete", 0).last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setIsDelete(1);
        model.setDeleteTime(System.currentTimeMillis() / 1000);
        storeMapper.updateById(model);
    }

    @Override
    public void status(StoreStatusValidate storeStatusValidate) {
        Store store = new Store();
        BeanUtils.copyProperties(storeStatusValidate, store);
        store.setUpdateTime(TimeUtils.timestamp());
        LambdaQueryWrapper<Store> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Store::getStoreId, store.getStoreId()).last("limit 1");
        storeMapper.update(store, wrapper);
    }

    @Override
    public AdminUserVo getAdminDetail(Integer userId) {
        SystemAuthAdmin admin = systemAuthAdminMapper.selectById(userId);
        AdminUserVo vo = null;
        if (Objects.nonNull(admin)) {
            vo = new AdminUserVo();
            vo.setUserId(userId);
            vo.setUsername(admin.getUsername());
            vo.setSalt(admin.getSalt());
        }
        return vo;
    }

}
